package com.app.common;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.app.model.AdminUserModel;
import com.app.model.FileModel;
import com.app.service.AdminUserService;
import com.app.service.FileService;
import com.app.utils.AliyunOSSUtils;
import com.app.utils.CommonHelp;
import com.app.utils.FileTypeUtil;
import com.app.utils.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Random;

@Slf4j
@RestController
@RequestMapping("/file")
public class UploadController {
    @Autowired
    private FileService fileService;
    @Autowired
    private AdminUserService adminUserService;
    @Autowired
    AliyunOSSUtils aliyunOSSUtils;
    @PostMapping("/upload")
    public Result<Object> upload(HttpServletRequest request,
                                 @RequestParam("file") MultipartFile file,
                                 @RequestParam(value = "moduleId",defaultValue = "0") Integer moduleId,
                                 @RequestParam(value = "businessId",required = false) Integer businessId
    ) throws IOException {
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        if ("false".equals(userId)) {
            return Result.error(405, "token已过期");
        }
        AdminUserModel user = adminUserService.getById(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(405, "用户不存在");
        }

        //上传文件路径
        String path = "";
        path = System.getProperty("user.dir") + File.separator + "file";
        //获得上传文件名
        String fileName = file.getOriginalFilename();
        int lastIndexOf = fileName.lastIndexOf(".");
        String date = IdUtil.getSnowflakeNextId()+"";
        //获取文件的后缀名 .jpg
        String suffix = fileName.substring(lastIndexOf);
        String suffix2 = fileName.substring(lastIndexOf + 1);
        String fileFullPath=path + File.separator + date + suffix;
        File filePath = new File(fileFullPath);
        System.out.println(filePath);
        //如果文件目录不存在，创建目录
        if (!filePath.getParentFile().exists()) {
            filePath.getParentFile().mkdirs();
        }
        //获取文件大小
        //将上传文件保存到一个目标文件中

//        file.transferTo(filePath);

        String fileURL = SystemConstant.DEFAULT_PDF_SERVICE_URL + date + suffix;
        String objectName = fileURL;

        try {
            aliyunOSSUtils.objectStorageUploadFile(objectName, file.getInputStream());
        } catch (Exception e){
            e.printStackTrace();
        }

        Integer fileType = FileTypeUtil.getFileType(suffix2);
        FileModel fileModel = new FileModel();
        fileModel.setFileType(fileType);
        fileModel.setName(date + suffix);
        fileModel.setUrl(fileURL);
        fileModel.setCreateTime(CommonHelp.getNowTimestamp());
        fileModel.setModuleId(moduleId);
        fileModel.setBusinessId(businessId);
        fileService.save(fileModel);
        return Result.success(fileModel);
    }


    @PostMapping("/userCommentUpload")
    public Result<Object> userCommentUpload(HttpServletRequest request, @RequestParam("file") MultipartFile file) throws IOException {
        //上传文件路径
        String path = "";
        path = System.getProperty("user.dir")+File.separator+"file";
        //获得上传文件名
        String fileName = file.getOriginalFilename();
        int lastIndexOf = fileName.lastIndexOf(".");
         String date = IdUtil.getSnowflakeNextId()+"";
        //获取文件的后缀名 .jpg
        String suffix = fileName.substring(lastIndexOf);
        String suffix2 = fileName.substring(lastIndexOf + 1);
        String fileFullPath=path + File.separator + date + suffix;
        File filePath = new File(fileFullPath);
        System.out.println(filePath);
        //如果文件目录不存在，创建目录
        if (!filePath.getParentFile().exists()) {
            filePath.getParentFile().mkdirs();
        }
        //获取文件大小
        //将上传文件保存到一个目标文件中
//        file.transferTo(filePath);
        String fileURL = SystemConstant.DEFAULT_PDF_SERVICE_URL + date + suffix;
        String objectName = fileURL;
        try {
            aliyunOSSUtils.objectStorageUploadFile(objectName, file.getInputStream());
        } catch (Exception e){
            e.printStackTrace();
        }

        Integer fileType = FileTypeUtil.getFileType(suffix2);
        FileModel fileModel = new FileModel();
        fileModel.setFileType(fileType);
        fileModel.setName(date + suffix);
        fileModel.setUrl(fileURL);
        fileModel.setCreateTime(CommonHelp.getNowTimestamp());
        return Result.success(fileModel);
    }

    //可以指定字符串的某个位置是什么范围的值
    public static String getRandomString2(int length) {
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(3);
            long result = 0;
            switch (number) {
                case 0:
                    result = Math.round(Math.random() * 25 + 65);
                    sb.append(String.valueOf((char) result));
                    break;
                case 1:
                    result = Math.round(Math.random() * 25 + 97);
                    sb.append(String.valueOf((char) result));
                    break;
                case 2:
                    sb.append(String.valueOf(new Random().nextInt(10)));
                    break;
            }
        }
        return sb.toString();
    }
}
